iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 1
0
自我挑戰組

霍普菜鳥的資訊工作雜記系列 第 25

D25-小試cordova ble的測試

  • 分享至 

  • xImage
  •  
'use strict';


Object.defineProperty(Object.prototype, 'reference', {
    value: function (A) {
        var key;
        for (key in A) {
            if (typeof A[key] === 'object') {
                if (this[key]) this[key].reference(A[key])
                else this[key] = A[key];
            }
            else this[key] = this[key] || A[key];
        };
    },
    enumerable: false,
});

var JSONBLEService = {
    service: "FFF0",
    InitJSON: "FFF1",
    JSONAccpeted: "FFF2",
    ReSetJSON: "FFF3",
    JsonKey: "FFF4",
    JsonValue: "FFF5",
    Exec: "FFF6",
    Params: "FFF7",
    ExecResult: "FFF8",
    Bt8ArrayData: "FFF9",
    Bt8ArrayLen: "FFFA",
    Bt8ArrayAccpeted: "FFFB",
    Bt8ArrayReSet: "FFFC"
};

var fileErrorHandler = function (fileName, e) {  
    var msg = '';
    switch (e.code) {
        case FileError.QUOTA_EXCEEDED_ERR:
            msg = 'Storage quota exceeded';
            break;
        case FileError.NOT_FOUND_ERR:
            msg = 'File not found';
            break;
        case FileError.SECURITY_ERR:
            msg = 'Security error';
            break;
        case FileError.INVALID_MODIFICATION_ERR:
            msg = 'Invalid modification';
            break;
        case FileError.INVALID_STATE_ERR:
            msg = 'Invalid state';
            break;
        default:
            msg = 'Unknown error';
            break;
    };
    app.log('Error (' + fileName + '): ' + msg);
}

var app = {
    peripheraID: "",
    jsstring: "",
    jsonValue: {},
    views: {},
    readTxtFromFile: function (fileName, cb) {
        var pathToFile = cordova.file.dataDirectory + fileName;
        window.resolveLocalFileSystemURL(pathToFile, function (fileEntry) {
            fileEntry.file(function (file) {
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    cb(this.result);
                };
                reader.readAsText(file);
            }, fileErrorHandler.bind(null, fileName));
        }, fileErrorHandler.bind(null, fileName));
    },
    writeTxtToFile : function(fileName, data) {
        window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (directoryEntry) {
            directoryEntry.getFile(fileName, { create: true }, function (fileEntry) {
                fileEntry.createWriter(function (fileWriter) {
                    fileWriter.onwriteend = function (e) {
                        app.log('Write of file "' + fileName + '"" completed.');
                    };
                    fileWriter.onerror = function (e) {
                        app.log('Write failed: ' + e.toString());
                    };
                    fileWriter.write(data);
                }, fileErrorHandler.bind(null, fileName));
            }, fileErrorHandler.bind(null, fileName));
        }, fileErrorHandler.bind(null, fileName));
    },
    initialize: function (viewName) {
        for (name in viewName)
            app.views[name] = document.getElementById(name);
        app.views.log.value = "[" + new Date().toLocaleTimeString() + "] " + "start";
    },
    log: function (l) {
        app.views.log.value += "\n[" + new Date().toLocaleTimeString() + "] " + l;
        app.views.log.scrollTop = app.views.log.scrollHeight;

    },
    onJsonValue: function (data) {
        var a = new Uint8Array(data);
        app.views.jsonvalue.value += "\n" + bytesToString(a);
        app.views.jsonvalue.scrollTop = app.views.jsonvalue.scrollHeight;

    },
    onJSONAccpeted: function (data) {
        var accepted = byteArrayToLong(data);
        var len = app.jsstring.length - accepted;
        var s;
        if (len > 20) {
            s = app.jsstring.substr(accepted, 20);
        }
        else {
            s = app.jsstring.substr(accepted, len);
            while (s.length < 20) s += "\0";
        }
        var attr = stringToBytes(s);
        for (var ii = 0; ii < attr.length; ii++) //check for non ASCII code
            if (attr[ii] > 127) { app.log("alarm[" + ii + "]at:[" + attr[ii] + "]"); retrun };

        if ((accepted < 1000) && (len > 0)) {
            ble.write(app.peripheraID, JSONBLEService.service, JSONBLEService.InitJSON,
                attr.buffer, function () { }, app.onError);
            //  app.log("JSON string to BLE continous:"+ accepted);    
        }
        else if (accepted > 1024)
            app.log("JSON passed! total token:" + (accepted - 1024))
        else app.log("Passing fail. Fail code:" + (accepted - 1024))

    },
    SetJsString: function (js) {
        var attr;
        try {
            app.jsstring = JSON.stringify(JSON.parse(js)) + "\0";
        }
        catch (err) {
            app.log(err.message); return
        };
        app.log("String length:" + app.jsstring.length);
        if (js.length > 1023) { app.log("chars of js string must less then 1024!"); return; };
        if (app.jsstring.length > 20) {
            var s = app.jsstring.substr(0, 20)
            attr = stringToBytes(s);
        }
        else {
            attr = stringToBytes(app.jsstring);
        };
        var attr2 = new Uint8Array(2);
        attr2[0] = 0; attr2[1] = 0;
        ble.write(app.peripheraID, JSONBLEService.service, JSONBLEService.ReSetJSON,
            attr2.buffer, function () { app.log("wait pass JSON to BLE!"); }, app.onError);

    },
    setJSKey: function (key) {
        if (key.length > 20) { app.log("JSON KEY length must less then 20!"); return; };
        var s = key;
        while (s.length < 20) s += "\0";
        var attr = stringToBytes(s);
        ble.write(app.peripheraID, JSONBLEService.service, JSONBLEService.JsonKey,
            attr.buffer, function () { app.log("setJSKey:" + s); }, app.onError);

    },
    deviceExec: function(cmd,params){
       device.app2ble(cmd);
    },
    text2bitmat: function (text) {
        var attr = new Uint8Array(702);

        return attr;
    },
    enableNotify: function () {
        ble.startNotification(app.peripheraID, JSONBLEService.service, JSONBLEService.JsonValue, app.onJsonValue, app.onError);
        ble.startNotification(app.peripheraID, JSONBLEService.service, JSONBLEService.JSONAccpeted, app.onJSONAccpeted, app.onError);
        app.log("enable notify!!")
    },
    refreshDevice: function (name, cb) {
        function connect(device) {
            if (device.name === name)
                ble.connect(device.id, function (e) {
                    app.peripheraID = device.id;
                    app.enableNotify();
                    cb()
                },app.onError);
        };
        ble.scan([], 5, connect, app.onError);
    },
    deviceList: function(name,cb){
        function addtolist(device) {
            if (device.name = name || device.name){
              devices.push({name: device.name ,RSSI: device.rssi,id: device.id,value:100-device.rssi});
              cb(devices);
            }
        };
        var devices =[];
        ble.scan([], 5, addtolist, app.onError);
    },
    disconnect: function (cb) {
        ble.disconnect(app.peripheraID, cb, app.onError);
    },
    onError: function (reason) {
        if (typeof reason === "object") app.log("ERROR: " + JSON.stringify(reason))
        else app.log("ERROR: " + reason); // real apps should use notification.alert
    }
};



上一篇
D24-試一下socket小練習
下一篇
D26-測試用d3 svg function 顯示圖示
系列文
霍普菜鳥的資訊工作雜記31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言